﻿using App.Channels;
using App.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Text.Json.Serialization;

namespace App
{
    public static class AppExtension
    {
        /// <summary>
        /// 默认开启
        /// 开启 IHttpContextAccessor
        /// 自动注入automapper
        /// 自动注入生命周期接口
        /// 注入控制器api模式
        /// 开启swagger
        /// 加载缓存中间件
        /// 消息队列
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="projectNames"></param>
        public static void UseAppExtension(this IServiceCollection services, string apiFilename)
        {
            // http context
            services.AddHttpContextAccessor();

            //自动注入automapper
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            // 生命周期
            services.RegisterLifeExtension();

            var controllers = services.AddControllers();

            if (!string.IsNullOrWhiteSpace(apiFilename))
            {
                services.AddEndpointsApiExplorer();
                services.UseAppSwaggerExtensin(new List<string>() { apiFilename });
            }

            // json 额外处理
            controllers.AddJsonOptions((option) =>
            {
                //时间格式化响应
                option.JsonSerializerOptions.Converters.Add(new JsonDateTimeConverter());
                option.JsonSerializerOptions.Converters.Add(new JsonTimeSpanConverter());

                // 空字符处理
                option.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
            });


            // 响应缓存中间件
            services.AddResponseCaching(options =>
             {
                 options.MaximumBodySize = 1024;
                 options.UseCaseSensitivePaths = true;
             });

            // 注入消息队列
            services.AddSingleton(typeof(IChannelMsg<>), typeof(ChannelMsg<>));
        }

        /// <summary>
        /// core 
        /// error
        /// swagger
        /// 重定向
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public static void UseAppExtension(this IApplicationBuilder app, IHostEnvironment env)
        {
            app.UseCors();
            app.UseError();
            app.UseAppSwagger(env, true);
            app.UseHttpsRedirection();

        }
    }
}
